<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Service\OpenShop\Feishu\ShopManualService;
use Illuminate\Console\Command;

class RefreshAllManual extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:refresh_all_manual {shopCode?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新所有的店铺的手册';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $shopCode = (string)$this->argument('shopCode');
        $total    = 0;
        $succeed  = 0;
        $failed   = 0;
        OpenShopSignOrderModel::query()
            ->when(strlen($shopCode), function ($query) use ($shopCode) {
                $query->where('shopCode', $shopCode);
            })
            ->whereIn('step', [SignOrderEnum::STEP_4, SignOrderEnum::STEP_5, SignOrderEnum::STEP_6])
//            ->where('payStatus', SignOrderEnum::PAY_STATUS_OK)
            ->whereIn(
                'status',
                [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE]
            )
            ->orderBy('id')
            ->chunk(100, function ($orders) use (&$total, &$succeed, &$failed) {
                foreach ($orders as $order) {
                    $total++;
                    if (!strlen($order->orderNo) || $order->shopCode < 1) {
                        $this->warn("订单ID:{$order->id}跳过，数据不完整");
                        $failed++;
                        continue;
                    }
                    $this->info("订单ID:{$order->id}，刷新手册中...");
                    (new ShopManualService($order->orderNo))->make($order->shopCode);
                    $succeed++;
                }
            });
        $this->info("");
        $this->info("成功:{$succeed}失败:{$failed}总计:{$total}");
        return 0;
    }
}
